package com.aiit.config;

import com.aiit.dao.IUserDao;
import com.aiit.pojo.User;
import com.aiit.service.IUserService;
import com.aiit.util.MD5utils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Configuration
public class MyRealm extends AuthorizingRealm {


    @Autowired
    private IUserDao dao;

    @Lazy
    @Autowired
    private IUserService userService;
    /**
     *用户认证的方法 这个方法不能手动调用shiro会自动调用
     *@parm authenticationToken 用户身份 这里存放用户的账号和密码
     *@return 用户登录成功后的身份证明
     *@throws AuthenticationException 如果失败shiro会抛出异常
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        String username=token.getUsername();//获取页面中传递的用户账号username
        User user= userService.getOne(new QueryWrapper<User>().eq("username", token.getUsername()));
//        User user= dao.queryByUsername(username);
        //把原密码加密
        String password= new String (token.getPassword());//实际中一般不获取密码
        System.out.println(username+"----------"+password);
        //认证账号,应从数据库获取,判断条件错误抛出异常
        if(user==null){
            throw new UnknownAccountException();
        }
//        //判断当前账号是否可用
//       if(!(user.getRole()==1)){
//           throw new LockedAccountException();
//       }


        //对当前数据库中的密码进行加密(同上)意义不大，主要加密用户登录密码
//        Object obj=new SimpleHash("MD5",user.getPassword(),"",1);//改变次数加密次数会改变密码

        /**
         *创建密码认证对象，由shiro自动认证密码
         *@parm 1-数据库中的账号 2-数据库中读取的密码  3-为当前Realm的名字
         *@return 如果密码认证成功则返回一个用户身份对象，如果密码认证失败shiro会抛出异常IncorrectCredentialsException()
         *@throws AuthenticationException
         */
//        return new SimpleAuthenticationInfo(user,obj,null,getName());
//        AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), null, getName());
        return new SimpleAuthenticationInfo(user,user.getPassword(),null,getName());

    }
}
